<?php

namespace Beike\Shop\Http\Controllers;

use Beike\Models\Product;
use Beike\Models\Category;
use Beike\Models\ProductCategory;
use Beike\Repositories\ProductRepo;
use Beike\Shop\Http\Resources\ProductDetail;
use Beike\Shop\Http\Resources\ProductSimple;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    /**
     * 商品详情页
     * @param Request $request
     * @param Product $product
     * @return mixed
     */
    public function show(Request $request, Product $product)
    {
        $relationIds = $product->relations->pluck('id')->toArray();
        $product     = ProductRepo::getProductDetail($product);

        // 如果 relations 为空，获取同一分类下的6个产品
        if (empty($relationIds)) {
            // 获取产品所属的分类ID
            $categoryIds = ProductCategory::where('product_id', $product->id)
                ->pluck('category_id')
                ->toArray();

            if (!empty($categoryIds)) {
                // 获取分类及其子分类的ID
                $allCategoryIds = collect($categoryIds);
                foreach ($categoryIds as $categoryId) {
                    $subCategoryIds = Category::where('parent_id', $categoryId)
                        ->where('active', 1)
                        ->pluck('id')
                        ->toArray();
                    $allCategoryIds = $allCategoryIds->merge($subCategoryIds);
                }

                // 查询同一分类或子分类中的产品
                $relationIds = ProductCategory::whereIn('category_id', $allCategoryIds)
                    ->join('products', 'product_categories.product_id', '=', 'products.id')
                    ->where('products.id', '!=', $product->id) // 排除当前产品
                    ->where('products.active', 1) // 确保产品启用
                    ->take(6)
                    ->pluck('products.id')
                    ->toArray();
            }
        }

        $data = [
            'product'   => (new ProductDetail($product))->jsonSerialize(),
            'relations' => ProductRepo::getProductsByIds($relationIds)->jsonSerialize(),
        ];

        $data = hook_filter('product.show.data', $data);

        return view('product', $data);
    }

    /**
     * 通过关键字搜索商品
     *
     * @param Request $request
     * @return mixed
     */
    public function search(Request $request)
    {
        $keyword  = $request->get('keyword');
        $attr     = $request->get('attr');
        $price    = $request->get('price');
        $products = ProductRepo::getBuilder(['keyword' => $keyword, 'attr' => $attr])
            ->where('active', true)
            ->paginate(perPage())
            ->withQueryString();

        $data = [
            'products' => $products,
            'items'    => ProductSimple::collection($products)->jsonSerialize(),
        ];

        $data = hook_filter('product.search.data', $data);

        return view('search', $data);
    }
}
